from flask import Flask, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from flask_cors import CORS
import os
from datetime import datetime
 
app = Flask(__name__)
CORS(app)  # 允许所有跨域请求
 
# 配置
UPLOAD_FOLDER = '/path/to/save'  # 替换为你希望保存文件的路径
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
 
# 从环境变量获取主机IP地址
HOST_IP = os.getenv('HOST_IP', '127.0.0.1')
 
# 确保上传文件夹存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
def get_timestamp_filename(filename):
   # 获取当前时间戳
   timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
   # 分离文件名和扩展名
   _, ext = os.path.splitext(filename)
   # 返回新的文件名
   return f"{timestamp}{ext}"
 
@app.route('/upload/file', methods=['POST'])
def upload_file():
   data = request.form
   print("AAAAAAAAAAAAA", request, request.files, data)
   if 'file' not in request.files:
       return jsonify({'error': 'No file part'}), 400
   file = request.files['file']
   if file.filename == '':
       return jsonify({'error': 'No selected file'}), 400
   filename = secure_filename(file.filename)
   new_filename = get_timestamp_filename(filename)
   file_path = os.path.join(app.config['UPLOAD_FOLDER'], new_filename)
   try:
       file.save(file_path)
   except Exception as e:
       app.logger.error(f"Failed to save file: {e}")
       return jsonify({'error': 'Failed to save file'}), 500
   download_url = f"http://{HOST_IP}:5007/files/{new_filename}"
   return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
 
@app.route('/files/<filename>', methods=['GET'])
def download_file(filename):
   try:
       return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
   except FileNotFoundError:
       return jsonify({'error': 'File not found'}), 404
 
if __name__ == '__main__':
   app.run(debug=True, host='0.0.0.0', port=5007)
